package com.chinaway.mobile.thread;

import java.util.Calendar;
import java.util.concurrent.Callable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chinaway.mobile.balance.impl.MobileBalanceSdImpl;
import com.chinaway.mobile.model.Account;
import com.chinaway.mobile.model.ResultMobileBean;
import com.chinaway.proxy.ProxyService;


public class MobileTask implements Callable<ResultMobileBean> {
	private final  Log log = LogFactory.getLog(getClass());
	public  String mobilekey = "sdmobile";
	private String mobile;
	private String city;
	private String password;
	private String appurl;
	private String appkey;
	private String method;
	private MobileBalanceSdImpl mobileBalanceSdImpl;
//	private MobileBalanceZjImpl mobileBalanceZjImpl=new MobileBalanceZjImpl();
	private String sddate=getSDDate();
	protected  ProxyService proxyService;
//	private String zjdate=getZJDate();

	
	public MobileTask(String mobile,String password,String city,String appurl,String appkey,String method,ProxyService proxyService) {
		this.mobile=mobile;
		this.password=password;
		this.city=city;
		this.appurl=appurl;
		this.appkey=appkey;
		this.method=method;
		this.proxyService=proxyService;
		mobileBalanceSdImpl=new MobileBalanceSdImpl(proxyService);
	}
	
	/*
	 * 爬取数据，分发结果
	 */
	@Override
	public ResultMobileBean call() {
		try{
			Account account=null;
			//爬数据，存入结果队列
			if("sd".equals(city)){
				account= mobileBalanceSdImpl.onlyAccount(mobile, password, sddate, proxyService.getProxy(mobilekey)) ;
				mobileBalanceSdImpl.setAccountCount(0);
				if(account!=null){
					return new ResultMobileBean(mobile, account.getBalance(),appurl,appkey,method,account.getSuccess(),account.getMessage());
				}
			}
		}catch(Exception e){
			//kill Thread
			log.info(mobile+"手机异常,释放当前线程，"+e.toString()+",Method="+e.getStackTrace()[0].getMethodName()+",Line="+ e.getStackTrace()[0].getLineNumber());
//			e.
			Thread.currentThread().interrupt();
			throw new RuntimeException(e.toString());
		}
		
		return new ResultMobileBean();
	}

	
	private String getSDDate(){
		Calendar a=Calendar.getInstance();
	    int year=a.get(Calendar.YEAR);//得到年
	    int month=a.get(Calendar.MONTH)+1;//由于月份是从0开始的所以加1
	    
		if(month<10){
			return year+"0"+month;
		} else{
			return year+""+month;
		}
	}
	
}
